<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\Common\Constants\ErrorCode;
use App\CustHub\Amqp\Producers\CrowdInviteProducer;
use App\CustHub\Amqp\Producers\CrowSendingProducers;
use App\CustHub\Amqp\Producers\SendRecordProducers;
use App\CustHub\Constants\CrowSendingConstants;
use App\CustHub\Constants\MsgTypeConstants;
use App\CustHub\Constants\RobotApplyConstants;
use App\CustHub\Constants\RoomInviteLogTypeConstants;
use App\CustHub\Constants\SendConfigConstants;
use App\CustHub\Constants\SendRecordStatusConstants;
use App\CustHub\Dto\AddMsgTemplateDto;
use App\CustHub\Dto\OperationLogDto;
use App\CustHub\Dto\SendRecordProducersDto;
use App\CustHub\Event\ChOperationLog;
use App\CustHub\Helpers\TagReplacer;
use App\CustHub\Mapper\ChContactMapper;
use App\CustHub\Mapper\ChCorpMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Mapper\ChRoomMapper;
use App\CustHub\Mapper\ChSendingMapper;
use App\CustHub\Mapper\ChSendRecordMapper;
use App\CustHub\Model\ChCorp;
use App\CustHub\Model\ChCrowdSending;
use App\CustHub\Model\ChCrowdSendingLoop;
use App\CustHub\Model\ChCrowdSendingSubTask;
use App\CustHub\Model\ChSendRecord;
use App\Exception\BusinessException;
use App\Robot\Dto\CommonJobDto;
use App\Robot\Dto\RobotMsgDto;
use App\Robot\Job\CommonJob;
use Carbon\Carbon;
use FriendsOfHyperf\Lock\Exception\LockTimeoutException;
use Hyperf\Amqp\Producer;
use Hyperf\DbConnection\Db;
use Itaoke\Logger;
use Mine\Abstracts\AbstractService;
use Hyperf\Di\Annotation\Inject;
use function FriendsOfHyperf\Lock\lock;
use function Hyperf\Coroutine\co;

class ChCrowSendingService extends AbstractService
{
    #[Inject]
    protected ChSendConfigService $sendService;

    #[Inject]
    protected ChRobotApplyService $applyService;

    #[Inject]
    protected ChContactService $contactService;

    #[Inject]
    protected ChRoomMapper $roomMapper;
    #[Inject]
    protected chCorpMapper $chCorpMapper;

    #[Inject]
    protected ChSendRecordService $sendRecordService;

    #[Inject]
    protected ChCorpTagService $corpTagService;

    #[Inject]
    protected ChRoomTagService $ChRoomTagService;

    #[Inject]
    protected ChSmartTagService $ChSmartTagService;

    public $mapper;

    public $sendingPauseCache='sendingPauseCache:';

    public function __construct(ChSendingMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function getSendingPauseCache(int $taskId)
    {
        return redis()->get($this->sendingPauseCache.$taskId);
    }

    public function setSendingPauseCache(int $taskId)
    {
        redis()->set($this->sendingPauseCache.$taskId,1);
    }

    public function clearSendingPauseCache(int $taskId)
    {
        redis()->del($this->sendingPauseCache.$taskId);
    }

    public function doCreateTaskV2(array $params = [])
    {
        try {
            $task_id = $params['task_id'];
            $taskInfo=ChCrowdSending::query()->where('id',$task_id)->first();
            $sendTimes = $taskInfo->send_times;
            //绑定机器人
            $targetIds = [$taskInfo->id];
            $robotIds = !is_array($params['robot_ids']) ? json_decode($params['robot_ids'], true) : $params['robot_ids'];
            if($robotIds){
                $robotIds=array_unique($robotIds);
                $this->applyService->batchApply($taskInfo->corp_id, $taskInfo->crowd_type, $targetIds, $robotIds, false);
            }
            $isSendNow = $sendTimes == 1;
            $customTotal = 0;
            $crowdTotal = 0;
            $lossTotal = 0;
            $isLastTask = false;
            $customIds=[];
            $crowdIds=[];
            foreach ($robotIds as $key=>$robotId)
            {
                $loss = 0;
                if ($taskInfo->send_type == 1) {
                    //按客户发送
                    $customRobotIds = $taskInfo->custom_ids;
                    $crowdRobotIds = $taskInfo->crowd_ids;
                    if ($customRobotIds) {
                        $customRobotInfo = array_filter($customRobotIds, function($item)use($robotId) {
                            return $item['robot_id'] == $robotId;
                        });
                        if(!empty($customRobotInfo)){
                            $customRobotInfo = reset($customRobotInfo) ?: [];
                            $customIds = $customRobotInfo['wxids'];
                            if (!$taskInfo->is_send_loss) {
                                //过滤流失好友
                                $notLossCustomIds = $this->contactService->getContactNotLoss($robotId, $customIds)->toArray();
                                $loss = count(array_diff($customIds, $notLossCustomIds));
                                $customIds = $notLossCustomIds;
                            }
                            $lossTotal += $loss;
                            $customTotal += count($customIds);
                        }
                    }
                    if ($crowdRobotIds) {
                        $crowdRobotInfo = array_filter($crowdRobotIds, function($item)use($robotId) {
                            return $item['robot_id'] == $robotId;
                        });
                        if(!empty($crowdRobotInfo)){
                            $crowdRobotInfo = reset($crowdRobotInfo) ?: [];
                            $crowdIds = $crowdRobotInfo['wxids'];
                            $crowdTotal += count($crowdIds);
                        }
                    }
                } else {
                    //按条件发送
                    //查询用户
                    $customIds = $this->getContactList($robotId, $taskInfo->uid, $taskInfo->condition_conf['custom_conf']);
                    //查询群
                    $crowdIds = $this->getCrowdList($robotId, $taskInfo->uid, $taskInfo->main_uid, $taskInfo->condition_conf['crowd_conf']);
                    if (!$taskInfo->is_send_loss) {
                        //过滤流失好友
                        $notLossCustomIds = $this->contactService->getContactNotLoss($robotId, $customIds)->toArray();
                        $loss = count(array_diff($customIds, $notLossCustomIds));
                        $customIds = $notLossCustomIds;
                    }
                    $lossTotal += $loss;
                    $crowdTotal += count($crowdIds);
                    $customTotal += count($customIds);
                }
                //生成子任务
                $subTask=ChCrowdSendingSubTask::setSubTask($robotId, $taskInfo->id, count($customIds), count($crowdIds), 0, 0, $loss);
                if ($key + 1 == count($robotIds)) {
                    $isLastTask = true;
                }
                //生成发送数据
                $customIds && $this->saveSendRecord($customIds, $taskInfo->uid, $taskInfo->main_uid, [$robotId], $taskInfo->crowd_type, $taskInfo->id, $subTask->id, time(), $taskInfo->content, 0, 0, $isLastTask);
                $crowdIds && $this->saveSendRecord($crowdIds, $taskInfo->uid, $taskInfo->main_uid, [$robotId], $taskInfo->crowd_type, $taskInfo->id, $subTask->id, time(), $taskInfo->content, 0, 1, $isLastTask);
                //生产发送队列
                if($isSendNow){
                    $data=[
                        'taskId'=>$task_id,
                        'subTaskId'=>$subTask->id,
                        'robotId'=>$robotId,
                        'isLastTask'=>$isLastTask,
                        'mainUid'=>$taskInfo->main_uid,
                        'uid'=>$taskInfo->uid,
                        'crowdType'=>$taskInfo->crowd_type,
                    ];
                    container()->get(Producer::class)->produce(new CrowSendingProducers($data));
                }

            }
            if ($crowdTotal == 0 && $customTotal == 0) {
                //如果发送对象为空直接完成
                //throw new BusinessException(ErrorCode::SERVICE_DELETE, '过滤流失好友后,发送对象为空');
                $taskInfo->status = CrowSendingConstants::COMPLETE;
            }
            //更新主表统计字段
            $taskInfo->crowd_total = $crowdTotal;
            $taskInfo->custom_total = $customTotal;
            $taskInfo->lose_total = $lossTotal;
            $taskInfo->save();

        } catch (\Throwable $ex) {
            logger()->info('群发错误'.$ex->getMessage());
        }
    }

    public function continueSend(int $task_id)
    {
        $task = ChCrowdSending::query()->where('id', $task_id)->first();
        $subTaskList = ChCrowdSendingSubTask::query()->where('crowd_sending_id', $task_id)->get();
        $isLastTask=false;
        foreach ($subTaskList as $key => $subTask) {
            if(count($subTaskList) == $key+1){
                $isLastTask = true;
            }
            $data=[
                'taskId'=>$task_id,
                'subTaskId'=>$subTask->id,
                'robotId'=>$subTask->robot_id,
                'isLastTask'=>$isLastTask,
                'mainUid'=>$task->main_uid,
                'uid'=>$task->uid,
                'crowdType'=>$task->crowd_type,
            ];
            container()->get(Producer::class)->produce(new CrowSendingProducers($data));
        }
    }



    public function sendRobotQueue(array $params = [])
    {
        try {
            $taskId = $params['taskId'];
            $subTaskId = $params['subTaskId'];
            $isLastTask = $params['isLastTask'];
            $robotId = $params['robotId'];
            $mainUId = $params['mainUid'];
            $uid = $params['uid'];
            $crowdType = $params['crowdType'];
            logger()->info('群发队列消费taskId-'.$taskId."subTaskId-".$subTaskId);
            if($crowdType == SendConfigConstants::SPEED_SENDING){
                //极速群发要区群和客户要分开发
                container()->get(ChSendRecordService::class)->sendByTaskIdPage((int)$robotId, (int)$taskId, (int)$subTaskId, (int)$mainUId,(int)$uid,(int)$crowdType,$isLastTask,1);
                container()->get(ChSendRecordService::class)->sendByTaskIdPage((int)$robotId, (int)$taskId, (int)$subTaskId, (int)$mainUId,(int)$uid,(int)$crowdType,$isLastTask,0);
            }else{
                container()->get(ChSendRecordService::class)->sendByTaskIdPage((int)$robotId, (int)$taskId, (int)$subTaskId, (int)$mainUId,(int)$uid,(int)$crowdType,$isLastTask);
            }

        } catch (\Throwable $ex) {
            logger()->info('群发队列错误'.$ex->getMessage());
        }
    }

    public function doCreateTask(array $params = [])
    {
        try {
            $sop_id = $params['sop_id'];
            $sopInfo=ChCrowdSending::query()->where('id',$sop_id)->first();
            $sendTimes = $sopInfo->send_times;
            //绑定机器人
            $targetIds = [$sopInfo->id];
            $robotIds = !is_array($params['robot_ids']) ? json_decode($params['robot_ids'], true) : $params['robot_ids'];
            if($robotIds){
                $robotIds=array_unique($robotIds);
                $this->applyService->batchApply($sopInfo->corp_id, $sopInfo->crowd_type, $targetIds, $robotIds, false);
            }
            $isSendNow = $sendTimes == 1;
            $startTime = time();
            if ($sendTimes == 2) {
                $startTime = strtotime($sopInfo->start_time);
            }
            $customTotal = 0;
            $crowdTotal = 0;
            $lossTotal = 0;
            if ($sopInfo->send_type == 1) {
                $customRobotIds = $sopInfo->custom_ids;
                $crowdRobotIds = $sopInfo->crowd_ids;
                $isLastTask = false;
                if ($customRobotIds) {
                    foreach ($customRobotIds as $key => $robotInfo) {
                        $loss = 0;
                        $customIds = $robotInfo['wxids'];
                        $robotId = $robotInfo['robot_id'];
                        if (empty($crowdRobotIds) && $key + 1 == count($customRobotIds)) {
                            $isLastTask = true;
                        }
                        if (!$sopInfo->is_send_loss) {
                            //过滤流失好友
                            $notLossCustomIds = $this->contactService->getContactNotLoss($robotId, $customIds)->toArray();
                            $loss = count(array_diff($customIds, $notLossCustomIds));
                            $customIds = $notLossCustomIds;
                        }
                        $lossTotal += $loss;
                        $customTotal += count($customIds);
                        $subTask = ChCrowdSendingSubTask::setSubTask($robotId, $sopInfo->id, count($customIds), 0, 0, $isSendNow ? 1 : 0, $loss);
                        $customIds && $this->sendRecord($customIds, $sopInfo->uid, $sopInfo->main_uid, [$robotId], $sopInfo->crowd_type, $sopInfo->id, $subTask->id, $startTime, $sopInfo->content, 0, 0, $isSendNow, $isLastTask);
                    }
                }
                if ($crowdRobotIds) {
                    foreach ($crowdRobotIds as $key => $robotInfo) {
                        $crowdIds = $robotInfo['wxids'];
                        $crowdTotal += count($crowdIds);
                        $robotId = $robotInfo['robot_id'];
                        $subTask = ChCrowdSendingSubTask::setSubTask($robotId, $sopInfo->id, 0, count($crowdIds), 0, $isSendNow ? 1 : 0);
                        if ($key + 1 == count($crowdRobotIds)) {
                            $isLastTask = true;
                        }
                        $crowdIds && $this->sendRecord($crowdIds, $sopInfo->uid, $sopInfo->main_uid, [$robotId], $sopInfo->crowd_type, $sopInfo->id, $subTask->id, $startTime, $sopInfo->content, 0, 1, $isSendNow, $isLastTask);
                    }
                }
            } else {
                $isLastTask = false;
                //创建发送对象
                if ($robotIds) {
                    foreach ($robotIds as $key => $robotId) {
                        $loss = 0;
                        //查询用户
                        $customIds = $this->getContactList($robotId, $sopInfo->uid, $sopInfo->condition_conf['custom_conf']);
                        //查询群
                        $crowdIds = $this->getCrowdList($robotId, $sopInfo->uid, $sopInfo->main_uid, $sopInfo->condition_conf['crowd_conf']);
                        if (!$sopInfo->is_send_loss) {
                            //过滤流失好友
                            $notLossCustomIds = $this->contactService->getContactNotLoss($robotId, $customIds)->toArray();
                            $loss = count(array_diff($customIds, $notLossCustomIds));
                            $customIds = $notLossCustomIds;
                        }
                        $lossTotal += $loss;
                        $crowdTotal += count($crowdIds);
                        $customTotal += count($customIds);
                        //生成子任务
                        $subTask = ChCrowdSendingSubTask::setSubTask($robotId, $sopInfo->id, count($customIds), count($crowdIds), 0, 0, $loss);
                        if (empty($crowdIds) && $key + 1 == count($robotIds)) {
                            $isLastTask = true;
                        }
                        $customIds && $this->sendRecord($customIds, $sopInfo->uid, $sopInfo->main_uid, [$robotId], $sopInfo->crowd_type, $sopInfo->id, $subTask->id, $startTime, $sopInfo->content, 0, 0, $isSendNow, $isLastTask);
                        if ($key + 1 == count($robotIds)) {
                            $isLastTask = true;
                        }
                        $crowdIds && $this->sendRecord($crowdIds, $sopInfo->uid, $sopInfo->main_uid, [$robotId], $sopInfo->crowd_type, $sopInfo->id, $subTask->id, $startTime, $sopInfo->content, 0, 1, $isSendNow, $isLastTask);

                    }
                }

            }
            if ($crowdTotal == 0 && $customTotal == 0) {
                //throw new BusinessException(ErrorCode::SERVICE_DELETE, '过滤流失好友后,发送对象为空');
                $sopInfo->status = CrowSendingConstants::COMPLETE;
            }
            //更新主表统计字段
            $sopInfo->crowd_total = $crowdTotal;
            $sopInfo->custom_total = $customTotal;
            $sopInfo->lose_total = $lossTotal;
            $sopInfo->save();
        } catch (\Throwable $ex) {
            logger()->info('群发错误'.$ex->getMessage());
        }
    }

    /**
     * 创建循环任务
     * @param $uid
     * @param $mainUid
     * @param array $data
     */
    public function createTask($uid, $mainUid, $data = [])
    {
        Db::beginTransaction();
        try {
            $sendTimes = $data['send_times'];
            if (in_array($sendTimes, [1, 2])) {
                $robotIds = !is_array($data['robot_ids']) ? json_decode($data['robot_ids'], true) : $data['robot_ids'];
                //直接生成群发任务
                $res = ChCrowdSending::saveCrowSending($uid, $mainUid, $data);
                $sendTimes = $res->send_times;
                //直接生成群发任务(避免定时任务重复执行，直接设置成发送中
                if ($sendTimes == 1) {
                    $res->status = CrowSendingConstants::SENDING;
                    $res->save();
                }
                Db::commit();
                //队列发送
                container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
                    classname: ChCrowSendingService::class,
                    method: 'doCreateTaskV2',
                    data: [
                        'task_id' => $res->id,
                        'robot_ids' => $data['robot_ids'],
                    ]
                )));
            } else {
                //生成循环任务
                $res = ChCrowdSendingLoop::saveCrowSendingLoop($uid, $mainUid, $data);
                $targetIds = [$res->id];
                $robotIds = !is_array($data['robot_ids']) ? json_decode($data['robot_ids'], true) : $data['robot_ids'];
                $robotIds && $this->applyService->batchApply(0, SendConfigConstants::SENDING_LOOP, $targetIds, $robotIds, false);
                foreach ($robotIds as $robotId) {
                    ChCrowdSendingSubTask::setSubTask($robotId, $res->id, 0, 0, 1);
                }
                Db::commit();
            }
            //添加日志
            $type = $data['send_type'] == 1 ? 101 : 102;
            $content = in_array($sendTimes, [1, 2]) ? '新建群发任务' : '新建群发循环任务';
            event((new ChOperationLog(
                (new OperationLogDto())
                    ->setUid($uid)
                    ->setMainUid($mainUid)
                    ->setSchemeId($res->id)
                    ->setName($data['title'])
                    ->setContent($content)
                    ->setType($type)
                    ->setRobotIds($robotIds)
            )));
            return $res;
        } catch (\Throwable $ex) {
            Db::rollBack();
            throw new BusinessException((int)$ex->getCode(), $ex->getMessage());
        }
    }

    /**
     * 给每个发送对象创建发送通道
     * @param array $objects
     * @param $uid
     * @param $mainUid
     * @param $robotIds
     * @param $sendType
     * @param $taskId
     * @param $startTime
     * @param $content
     * @param int $isRoom
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function sendRecord(array $objects, $uid, $mainUid, $robotIds, $sendType, $taskId, $subTaskId, $startTime, $content, $delay = 0, $isRoom = 0, $isSendNow = false, $isLastSubTask = false, $changeData = true)
    {
        if (!empty($robotIds)) {
            //创建发送对象
            $recordData = [];
            $labels = [];
            $extra = null;
            $delay && $extra = ['delay' => $delay];
            //个人去除@所有人
            if ($changeData && !$isRoom) {
                foreach ($content as $key => $item) {
                    if (!is_string($item['content'])) {
                        continue;
                    }
                    if ($item['msg_type'] == 'text' && str_contains($item['content'], '{@所有人}')) {
                        $content[$key]['content'] = str_replace("{@所有人}", '', $item['content']);
                    }
                }
            }else{
                foreach ($content as $key => $item) {
                    if (!is_string($item['content'])) {
                        continue;
                    }
                    if ($item['msg_type'] == 'text' && str_contains($item['content'], '{昵称}')) {
                        $content[$key]['content'] = str_replace("{昵称}", '', $item['content']);
                    }
                    if ($item['msg_type'] == 'text' && str_contains($item['content'], '{称呼/昵称}')) {
                        $content[$key]['content'] = str_replace("{称呼/昵称}", '', $item['content']);
                    }
                }
            }
            foreach ($robotIds as $robotId) {
                foreach ($objects as $object) {
                    if ($changeData && !$isRoom) {
                        $contactInfo = container()->get(ChContactMapper::class)->findByRobotIdAndUserId((int)$robotId, (string)$object);
                        $nickname = !empty($contactInfo->nickname) ? $contactInfo->nickname : '';
                        $labels = [
                            'call_name_nickname' => !empty($contactInfo->call_name) ? $contactInfo->call_name : $contactInfo->nickname,
                            'nickname' => $nickname,
                            'receiver' => $object
                        ];
                    }
                    $sendContent = $changeData ? TagReplacer::changeData($content, $labels) : $content;
                    $recordData[] = [
                        'uid' => $uid,
                        'main_uid' => $mainUid,
                        'task_id' => $taskId,
                        'sub_task_id' => $subTaskId,
                        'robot_id' => $robotId,
                        'to_id' => $object,
                        'trigger_time' => $startTime,
                        'content' => $sendContent,
                        'msg_total_count' => count($content),
                        'type' => $sendType,
                        'is_room' => $isRoom,
                        'extra' => $extra
                    ];
                }
            }
            container()->get(Producer::class)->produce(new SendRecordProducers(
                (new SendRecordProducersDto())
                    ->setMainUid($mainUid)
                    ->setUid((int)$uid)
                    ->setTaskId($taskId)
                    ->setSubTaskId($subTaskId)
                    ->setType($sendType)
                    ->setIsLastSubTask($isLastSubTask)
                    ->setIsRoom($isRoom)
                    ->setRecordData($recordData)
                    ->setIsSendNow($isSendNow)
            ));
        }
    }


    public function saveSendRecord(array $objects, $uid, $mainUid, $robotIds, $sendType, $taskId, $subTaskId, $startTime, $content, $delay = 0, $isRoom = 0, $isLastSubTask = false, $changeData = true)
    {
        if (!empty($robotIds)) {
            //创建发送对象
            $recordData = [];
            $labels = [];
            $extra = null;
            $delay && $extra = ['delay' => $delay];
            //个人去除@所有人
            if ($changeData && !$isRoom) {
                foreach ($content as $key => $item) {
                    if (!is_string($item['content'])) {
                        continue;
                    }
                    if ($item['msg_type'] == 'text' && str_contains($item['content'], '{@所有人}')) {
                        $content[$key]['content'] = str_replace("{@所有人}", '', $item['content']);
                    }
                }
            }else{
                foreach ($content as $key => $item) {
                    if (!is_string($item['content'])) {
                        continue;
                    }
                    if ($item['msg_type'] == 'text' && str_contains($item['content'], '{昵称}')) {
                        $content[$key]['content'] = str_replace("{昵称}", '', $item['content']);
                    }
                    if ($item['msg_type'] == 'text' && str_contains($item['content'], '{称呼/昵称}')) {
                        $content[$key]['content'] = str_replace("{称呼/昵称}", '', $item['content']);
                    }
                }
            }
            foreach ($robotIds as $robotId) {
                foreach ($objects as $object) {
                    if ($changeData && !$isRoom) {
                        $contactInfo = container()->get(ChContactMapper::class)->findByRobotIdAndUserId((int)$robotId, (string)$object);
                        $nickname = !empty($contactInfo->nickname) ? $contactInfo->nickname : '';
                        $labels = [
                            'call_name_nickname' => !empty($contactInfo->call_name) ? $contactInfo->call_name : $contactInfo->nickname,
                            'nickname' => $nickname,
                            'receiver' => $object
                        ];
                    }
                    $sendContent = $changeData ? TagReplacer::changeData($content, $labels) : $content;
                    $recordData[] = [
                        'uid' => $uid,
                        'main_uid' => $mainUid,
                        'task_id' => $taskId,
                        'sub_task_id' => $subTaskId,
                        'robot_id' => $robotId,
                        'to_id' => $object,
                        'trigger_time' => $startTime,
                        'content' => $sendContent,
                        'msg_total_count' => count($content),
                        'type' => $sendType,
                        'is_room' => $isRoom,
                        'extra' => $extra
                    ];
                }
            }
            container()->get(ChSendRecordService::class)->addRecord((new SendRecordProducersDto())
                ->setMainUid($mainUid)
                ->setUid((int)$uid)
                ->setTaskId($taskId)
                ->setSubTaskId($subTaskId)
                ->setType($sendType)
                ->setIsLastSubTask($isLastSubTask)
                ->setIsRoom($isRoom)
                ->setRecordData($recordData)
                ->setIsSendNow(false)
                ->toArray());
        }
    }

    /**
     * 遍历循环任务 根据时间创建群发任务
     */
    public function loop()
    {
        //1执行中  2已完成 3暂停中  4已取消
        $time = time();
        $last_date = datetime($time, "Ymd");
        ChCrowdSendingLoop::query()->where('status', 1)->where(function ($q) use ($last_date) {
            $q->where('last_date', '!=', $last_date)->orWhereNull('last_date');
        })->chunk(100, function ($loops) use ($time, $last_date) {
            foreach ($loops as $loop) {
                //自动完成全部
                if ($loop->is_loop_end == 1 && !empty($loop->loop_end_time) && $time > strtotime($loop->loop_end_time)) {
                    $loop->status = CrowSendingConstants::COMPLETE;
                    $loop->last_date = $last_date;
                    $loop->save();
                    //完成子任务
                    ChCrowdSendingSubTask::query()->where('is_loop', 1)->where('crowd_sending_id', $loop->id)->update([
                        'status' => CrowSendingConstants::COMPLETE
                    ]);
                    continue;
                }
                if ($this->checkTimesConf($loop, $time)) {
                    $res = ChCrowdSending::saveCrowSending($loop->uid, $loop->main_uid, $loop->toArray(), 0, $loop->id, date("Y-m-d H:i:s", $time));
                    if ($res !== false) {
                        //同步应用机器人
                        $targetIds = [$res->id];
                        $robotIds = $this->applyService->getApplyRobot(RobotApplyConstants::SENDING_LOOP, $loop->id);
                        var_dump($robotIds);
                        $robotIds && $this->applyService->batchApply($res->corp_id, $res->crowd_type, $targetIds, $robotIds, false);
                        //循环是否截止截止
                        if ($loop['is_loop_end'] == 1 && $loop['loop_end_time'] <= time()) {
                            $loop->status = CrowSendingConstants::COMPLETE;
                        }
                    }
                    $loop->last_date = $last_date;
                    $loop->save();
                }

            }
        });

    }


    /**
     * 检测是否满足发送条件
     * @param ChCrowdSendingLoop $loop
     * @param $time
     * @return bool
     */
    public function checkTimesConf(ChCrowdSendingLoop $loop, $time)
    {
        $flag = false;
        $timesConf = $loop->send_times_conf;
        $sendTimes = $loop->send_times;
        switch ($sendTimes) {
            case 1:
                break;
            case 2:
                break;
            case 3:
                //当天，允许1分钟误差
                $sendTime = str_replace(":", '', $timesConf['time']);
                if ($sendTime <= date("Hi", $time) && $sendTime+5 > date("Hi", $time)) {
                    $flag = true;
                }
                break;
            case 4:
                //本周
                $week = date("w");
                $sendTime = str_replace(":", '', $timesConf['time']);
                if (in_array($week, $timesConf['day']) && $sendTime <= date("Hi", $time) && $sendTime+5 > date("Hi", $time)) {
                    $flag = true;
                }
                break;
            case 5:
                //本月
                $d = date("d");
                $sendTime = str_replace(":", '', $timesConf['time']);
                if (in_array($d, $timesConf['day']) && $sendTime <= date("Hi", $time) && $sendTime+5 > date("Hi", $time)) {
                    $flag = true;
                }
                break;
        }
        return $flag;
    }


    /**
     * 处理群发任务
     */
    public function sendingProcess()
    {
        ChCrowdSending::query()->where('status', CrowSendingConstants::WAIT_SEND)->where('start_time', '<=', date("Y-m-d H:i:s", time()))->chunk(100, function ($sendings) {
            foreach ($sendings as $sending) {
                $sending->status=CrowSendingConstants::SENDING;
                $sending->save();
                $lock = lock('crowd_sending_process:'.$sending->id,4);
                try {
                    //获取锁
                    if(!$lock->get()){
                        var_dump('获取锁失败'.$sending->id);
                       throw new LockTimeoutException('获取锁失败');
                    }
                    $isLastTask = false;
                    if ($sending->send_times == 2) {
                        //获取子任务
                        $subTaskList = ChCrowdSendingSubTask::query()->where('crowd_sending_id', $sending->id)->get();
                        foreach ($subTaskList as $key => $subTask) {
                            if(count($subTaskList) == $key+1){
                                $isLastTask = true;
                            }
                            $data=[
                                'taskId'=>$sending->id,
                                'subTaskId'=>$subTask->id,
                                'robotId'=>$subTask->robot_id,
                                'isLastTask'=>$isLastTask,
                                'mainUid'=>$sending->main_uid,
                                'uid'=>$sending->uid,
                                'crowdType'=>$sending->crowd_type,
                            ];
                            container()->get(Producer::class)->produce(new CrowSendingProducers($data));
                        }
                        continue;
                    }
                    //获取所有应用机器人
                    $robotIds = $this->applyService->getApplyRobot($sending->crowd_type, $sending->id);

                    $customTotal = 0;
                    $crowdTotal = 0;
                    $lossTotal = 0;
                    $customIds=[];
                    $crowdIds=[];

                    foreach ($robotIds as $key=>$robotId)
                    {
                        $loss = 0;
                        if ($sending->send_type == 1) {
                            //按客户发送
                            $customRobotIds = $sending->custom_ids;
                            $crowdRobotIds = $sending->crowd_ids;
                            if ($customRobotIds) {
                                $customRobotInfo = array_filter($customRobotIds, function($item)use($robotId) {
                                    return $item['robot_id'] == $robotId;
                                });
                                if(!empty($customRobotInfo)){
                                    $customRobotInfo = reset($customRobotInfo) ?: [];
                                    $customIds = $customRobotInfo['wxids'];
                                    if (!$sending->is_send_loss) {
                                        //过滤流失好友
                                        $notLossCustomIds = $this->contactService->getContactNotLoss($robotId, $customIds)->toArray();
                                        $loss = count(array_diff($customIds, $notLossCustomIds));
                                        $customIds = $notLossCustomIds;
                                    }
                                    $lossTotal += $loss;
                                    $customTotal += count($customIds);
                                }
                            }

                            if ($crowdRobotIds) {
                                $crowdRobotInfo = array_filter($crowdRobotIds, function($item)use($robotId) {
                                    return $item['robot_id'] == $robotId;
                                });
                                if(!empty($crowdRobotInfo)){
                                    $crowdRobotInfo = reset($crowdRobotInfo) ?: [];
                                    $crowdIds = $crowdRobotInfo['wxids'];
                                    $crowdTotal += count($crowdIds);
                                }
                            }
                        } else {
                            //按条件发送
                            //查询用户
                            $customIds = $this->getContactList($robotId, $sending->uid, $sending->condition_conf['custom_conf']);
                            //查询群
                            $crowdIds = $this->getCrowdList($robotId, $sending->uid, $sending->main_uid, $sending->condition_conf['crowd_conf']);
                            if (!$sending->is_send_loss) {
                                //过滤流失好友
                                $notLossCustomIds = $this->contactService->getContactNotLoss($robotId, $customIds)->toArray();
                                $loss = count(array_diff($customIds, $notLossCustomIds));
                                $customIds = $notLossCustomIds;
                            }
                            $lossTotal += $loss;
                            $crowdTotal += count($crowdIds);
                            $customTotal += count($customIds);
                        }
                        //生成子任务
                        $subTask=ChCrowdSendingSubTask::setSubTask($robotId, $sending->id, count($customIds), count($crowdIds), 0, 0, $loss);
                        if ($key + 1 == count($robotIds)) {
                            $isLastTask = true;
                        }
                        //生成发送数据
                        $customIds && $this->saveSendRecord($customIds, $sending->uid, $sending->main_uid, [$robotId], $sending->crowd_type, $sending->id, $subTask->id, time(), $sending->content, 0, 0, $isLastTask);
                        $crowdIds && $this->saveSendRecord($crowdIds, $sending->uid, $sending->main_uid, [$robotId], $sending->crowd_type, $sending->id, $subTask->id, time(), $sending->content, 0, 1, $isLastTask);
                        //生产发送队列
                        $data=[
                            'taskId'=>$sending->id,
                            'subTaskId'=>$subTask->id,
                            'robotId'=>$robotId,
                            'isLastTask'=>$isLastTask,
                            'mainUid'=>$sending->main_uid,
                            'uid'=>$sending->uid,
                            'crowdType'=>$sending->crowd_type,
                        ];
                        container()->get(Producer::class)->produce(new CrowSendingProducers($data));
                    }
                    if ($crowdTotal == 0 && $customTotal == 0) {
                        //如果发送对象为空直接完成
                        //throw new BusinessException(ErrorCode::SERVICE_DELETE, '过滤流失好友后,发送对象为空');
                        $sending->status = CrowSendingConstants::COMPLETE;
                    }
                    //更新主表统计字段
                    $sending->crowd_total = $crowdTotal;
                    $sending->custom_total = $customTotal;
                    $sending->lose_total = $lossTotal;
                    $sending->save();
                }catch (LockTimeoutException $e) {
                    //超时
                    logger()->info('群发任务执行失败' . $sending->id.':获取锁超时');
                    continue;
                } catch (\Throwable $ex) {
                    //跳过该任务，并且直接完成
                    $sending->status = CrowSendingConstants::COMPLETE;
                    $sending->save();
                    logger()->info('群发任务执行失败' . $sending->id.':错误原因'.$ex->getMessage());
                    continue;
                }finally {
                    $lock->release();
                }
            }
        });
    }

    /**
     * 获取任务日历统计数据
     * @param array|null $params
     * @return array
     */
    public function getTaskList(?array $params = []): array
    {
        return $this->mapper->getTaskList($params['uid'], $params['date'], $params['task_type'], $params['status']);
    }

    public function getContactList($robotId, $uid, $custom_conf = [])
    {
        if (empty($custom_conf)) return [];
        $map = [];
        $map['uid'] = $uid;
        $map['robot_ids'] = [$robotId];
        $customIds = [];
        if(empty($custom_conf['type'])){
            return [];
        }
        if ($custom_conf['type'] == 1) {
            $list = $this->contactService->getContactsByFilter($map,["*"],false);
            $customIds = array_column($list, 'user_id');
        } else {
            if (empty($custom_conf['conf'])) return [];
            $conf = $custom_conf['conf'];
            foreach ($conf as $key => $item) {
                $queryMap = [];
                //加好友时间
                !empty($item['isset']['add_start_time']) && $queryMap['add_start_time'] = $item['isset']['add_start_time'];
                !empty($item['isset']['add_end_time']) && $queryMap['add_end_time'] = $item['isset']['add_end_time'];
                //备注
                if(not_empty($item['isset']['is_with_remarks'])){
                    $queryMap['is_with_remarks'] = $item['isset']['is_with_remarks'];
                    $queryMap['remarks'] = $item['isset']['remarks'];
                    $queryMap['remark_type'] = !empty($item['isset']['remark_type'])?:2;
                }
                //性别
                not_empty($item['isset']['gender']) && $queryMap['gender'] = $item['isset']['gender'];
                //企业标签
                $corp_tag = [
                    'exclude_switch' => $item['exclude_switch'],
                ];
                if (isset($item['isset']['corp_match_type']) && !empty($item['isset']['corp_tag_ids'])) {
                    if(!empty($item['isset']['corp_tag_ids'][0]['corp_id'])){
                        $corp_tag_ids = array_unique(array_merge(...array_column($item['isset']['corp_tag_ids'], 'ids')));
                    }else{
                        $corp_tag_ids=$item['isset']['corp_tag_ids'];
                    }
                    $corp_tag['include_match_type']=$item['isset']['corp_match_type'];
                    $corp_tag['include_tag_ids']=$corp_tag_ids;
                }
                if ($item['exclude_switch'] == 1 && !empty($item['out']['corp_tag_ids'])) {
                    if(!empty($item['out']['corp_tag_ids'][0]['corp_id'])){
                        $corp_tag_ids = array_unique(array_merge(...array_column($item['out']['corp_tag_ids'], 'ids')));
                    }else{
                        $corp_tag_ids=$item['out']['corp_tag_ids'];
                    }
                    $corp_tag['exclude_match_type'] = $item['out']['corp_match_type'];
                    $corp_tag['exclude_tag_ids'] = $corp_tag_ids;
                }
                $queryMap['corp_tag'] = $corp_tag;
                //智能标签
                $smart_tag = [
                    'exclude_switch' => $item['exclude_switch'],
                ];
                if (isset($item['isset']['smart_match_type']) && !empty($item['isset']['smart_tag_ids'])) {
                    $smart_tag['include_match_type']=$item['isset']['smart_match_type'];
                    $smart_tag['include_tag_ids']=$item['isset']['include_tag_ids'];
                }
                if ($item['exclude_switch'] == 1) {
                    $smart_tag['exclude_match_type'] = $item['out']['smart_match_type'];
                    $smart_tag['exclude_tag_ids'] = $item['out']['smart_tag_ids'];

                }
                $queryMap['smart_tag'] = $smart_tag;
                //var_dump($queryMap);
                $list = $this->contactService->getContactsByFilter(array_merge($map, $queryMap),["*"],false);
                //手动去除不符合的
                if ($item['exclude_switch'] == 1 && !empty($list)) {
                    $newList = [];
                    foreach ($list as $subItem) {
                        //排除时间
                        if (!empty($item['out']['add_start_time'])) {
                            if ($subItem['add_customer_time'] < strtotime($item['out']['add_start_time'])) {
                                continue;
                            }
                        }
                        if (!empty($item['out']['add_end_time'])) {
                            if ($subItem['add_customer_time'] > strtotime($item['out']['add_end_time'])) {
                                continue;
                            }
                        }
                        //排除备注
                        if (not_empty($item['out']['is_with_remarks'])) {
                            if ($item['out']['is_with_remarks'] === 0 && empty($subItem['remark'])) {
                                continue;
                            }
                            if ($item['out']['is_with_remarks'] === 1) {
                                //没有填写备注关键词，排除所有有备注的
                                if(empty($item['out']['remarks']) && !empty($subItem['remark'])){
                                    continue;
                                }
                                //有备注关键词，排除填写的
                                if(!empty($item['out']['remarks']) && in_array($subItem['remark'], $item['out']['remarks'])){
                                    continue;
                                }
                            }
                        }
                        //排除性别
                        if (not_empty($item['out']['gender'])) {

                            if ($item['out']['gender'] === 0 && $subItem['gender'] === 0) {
                                continue;
                            }
                            if ($item['out']['gender'] === 1 && $subItem['gender'] === 1) {
                                continue;
                            }
                            if ($item['out']['gender'] === 2 && $subItem['gender'] === 2) {
                                continue;
                            }
                        }
                        $newList[] = $subItem;
                    }
                    $list = $newList;
                }
                $subCustomIds = array_column($list, 'user_id');
                if ($key == 0 || $item['op'] == 'or') {
                    //取并集
                    $customIds = array_values(array_unique(array_merge($customIds, $subCustomIds)));
                } else {
                    //取交集
                    $customIds = array_values(array_intersect($customIds, $subCustomIds));
                }
            }
        }
        return $customIds;
    }


    public function getCrowdList($robotId, $uid, $main_uid, $crowd_conf = [])
    {
        if (empty($crowd_conf)) return [];
        $map = [];
        $map['uid'] = $uid;
        $map['robot_id'] = $robotId;
        $map['main_uid'] = $main_uid;
        $crowdIds = [];
        if(empty($crowd_conf['type'])){
            return [];
        }
        if ($crowd_conf['type'] == 1) {
            $roomList = $this->roomMapper->getRoomList($map)->toArray();
            $crowdIds = array_column($roomList, 'room_wxid');
        } else {
            if (empty($crowd_conf['conf'])) return [];
            $conf = $crowd_conf['conf'];
            foreach ($conf as $key => $item) {
                $queryMap = [];
                !empty($item['isset']) && $queryMap['include_params'] = $item['isset'];
                !empty($item['out']) && $queryMap['exclude_params'] = $item['out'];
                $roomList = $this->roomMapper->getRoomList(array_merge($map, $queryMap))->toArray();
                $subCustomIds = array_column($roomList, 'room_wxid');
                if ($key == 0 || (!empty($item['op']) && $item['op'] == 'or')) {
                    //取并集
                    $crowdIds = array_values(array_unique(array_merge($crowdIds, $subCustomIds)));
                } else {
                    //取交集
                    $crowdIds = array_values(array_unique(array_intersect($crowdIds, $subCustomIds)));
                }
            }
        }
        return $crowdIds;
    }


    public function speedSendMessageV2(array $data,$list)
    {
        $robotId = $data['robot_id'];
        $taskId = $data['task_id'];
        $isRoom = $data['is_room'];
        $isEnd = $data['is_end'];
        $subTaskId = $data['sub_task_id'];
        $isSubEnd = $data['is_last_sub_task'];
        $sendType = $isRoom;

        $sending = ChCrowdSending::find($taskId);
        $subTask = ChCrowdSendingSubTask::find($subTaskId);
        if (empty($sending) || empty($subTask)){
            logger()->info('极速群发任务不存在taskId:'.$taskId.'-subTaskId.'.$subTaskId.'start-end');
            return false;
        }
        $chatIdList = $list->pluck('to_id');
        $sendRecordList = $list->pluck('id');
        try {
            if ($chatIdList->isEmpty()){
                $subTask->status = CrowSendingConstants::COMPLETE;
                if ($isEnd) {
                    $sending->status = CrowSendingConstants::COMPLETE;
                    $sending->end_time = datetime(time());
                }
                $subTask->save();
                $sending->save();
                return false;
            }
            $chatIdList=$chatIdList->toArray();
            $total = count($chatIdList);
            $subTask->increment('complete_total', $total);
            $sending->increment('complete_total', $total);

            $text = $sending->speed_text;
            $attachments = $sending->content;
            $content = [];
            if(!empty($text)){
                $content[] = [
                    'msg_type' => 'text',
                    'content' => $text
                ];
            }
            if(!empty($attachments)){
                $content=array_merge($content, $attachments);
            }

            $robotInfo = container()->get(ChRobotMapper::class)-> findById($robotId);
            $msgData = new RobotMsgDto();
            $msgData->setMsgType(MsgTypeConstants::SPEED)
                ->setContent($content)
                ->setToIdList($chatIdList)
                ->setSendType($sendType)
                ->setServerId($robotInfo->server_id)
                ->setUuid($robotInfo->uuid);
            $result = make(\App\Robot\Service\RobotMessageService::class, [$msgData])->sendSpeedMessage();
            if ($result['status']) {
                $newToList = $result['newToList'];
                $diffList = array_diff($chatIdList, $newToList);
                //成功
                $subTask->increment('success_total', count($newToList));
                $sending->increment('success_total', count($newToList));
                //失败
                $subTask->increment('fail_total', count($diffList));
                $sending->increment('fail_total', count($diffList));

                ChSendRecord::query()->whereIn('id',$sendRecordList)->whereIn('to_id',$newToList)->update(['status' => SendRecordStatusConstants::SUCCESS]);
                ChSendRecord::query()->whereIn('id',$sendRecordList)->whereIn('to_id',$diffList)->update(['status' => SendRecordStatusConstants::FAILURE,'failure_reason'=>'检测出今日已经不可发送']);
            } else {
                $subTask->fail_total = $subTask->fail_total + $total;
                $sending->fail_total = $sending->fail_total + $total;
                $errorMessage=!empty($result['errorMessage'])?$result['errorMessage']:'协议错误';
                ChSendRecord::query()->whereIn('id',$sendRecordList)->update(['status' => SendRecordStatusConstants::FAILURE,'failure_reason'=>$errorMessage]);
            }
            $subTask->status = CrowSendingConstants::COMPLETE;

            if ($isEnd) {
                $sending->status = CrowSendingConstants::COMPLETE;
                $sending->end_time = datetime(time());
            }
            $subTask->save();
            $sending->save();
        }catch (\Throwable $e){
            logger()->info('极速群发发送失败taskId:'.$taskId.'-subTaskId.'.$subTaskId.":".$e->getMessage());
            ChSendRecord::query()->whereIn('id',$sendRecordList)->update(['status' => SendRecordStatusConstants::FAILURE,'failure_reason'=>$e->getMessage()]);
            $subTask->status = CrowSendingConstants::COMPLETE;

            if ($isEnd) {
                $sending->status = CrowSendingConstants::COMPLETE;
                $sending->end_time = datetime(time());
            }
            $subTask->save();
            $sending->save();
        }

    }

    /**
     * 极速群发发送
     */
    public function speedSendMessage(array $data)
    {
        var_dump('极速群发队列参数');
        var_dump($data);
        $robotId = $data['robot_id'];
        $taskId = $data['task_id'];
        $isRoom = $data['is_room'];
        $isEnd = $data['is_end'];
        $isSubEnd = $data['is_sub_end'];
        $subTaskId = $data['sub_task_id'];
        $chatType = 'single';
        if ($isRoom == 1) {
            $chatType = "group";
        }
        $sending = ChCrowdSending::query()->where('id', $taskId)->first();
        $subTask = ChCrowdSendingSubTask::query()->where('id', $subTaskId)->first();
        if (empty($sending)) return false;
        $start = $data['start'];
        $limit = $data['limit'];
        $chatIdList = $externalUserid = ChSendRecord::query()->where('sub_task_id', $subTaskId)->where('status', SendRecordStatusConstants::SENDING)->offset($start)->limit($limit)->pluck('to_id')->toArray();
        if (empty($chatIdList)) return false;
        $total = count($chatIdList);
        $text = $sending->speed_text;
        $attachments = $sending->content;
        $data = (new AddMsgTemplateDto())
            ->setChatType($chatType)
            ->setText([
                "content" => $text
            ])
            ->setAttachments($attachments);
        if ($isRoom) {
            $data->setChatIdList($chatIdList);
        } else {
            $data->setExternalUserid($externalUserid);
        }
        $corpInfo = container()->get(ChCorpMapper::class)->findById($sending->corp_id);
        if (!empty($corpInfo->auth_corp_id)){
            $result = make(\App\Robot\Service\SpeedMessageService::class, [$data, $corpInfo->auth_corp_id, (int)$robotId])->sendMessage();

            if ($result) {
                $subTask->success_total = $subTask->success_total + $total;
                $sending->success_total = $sending->success_total + $total;
                ChSendRecord::query()->where('sub_task_id', $subTaskId)->offset($start)->limit($limit)->update(['status' => SendRecordStatusConstants::SUCCESS]);
            } else {
                $subTask->fail_total = $subTask->fail_total + $total;
                $sending->fail_total = $sending->fail_total + $total;
                ChSendRecord::query()->where('sub_task_id', $subTaskId)->offset($start)->limit($limit)->update(['status' => SendRecordStatusConstants::FAILURE]);
            }
            if ($isSubEnd) {
                $subTask->status = CrowSendingConstants::COMPLETE;
            }
            if ($isEnd) {
                $sending->status = CrowSendingConstants::COMPLETE;
                $sending->end_time = datetime(time());
            }
        }else{
            ChSendRecord::query()->where('sub_task_id', $subTaskId)->offset($start)->limit($limit)->update(['status' => SendRecordStatusConstants::FAILURE,'failure_reason'=>'企业未授权']);

            if ($isSubEnd) {
                $subTask->status = CrowSendingConstants::COMPLETE;
            }
            if ($isEnd) {
                $sending->status = CrowSendingConstants::COMPLETE;
                $sending->end_time = datetime(time());
            }
        }
        $subTask->save();
        $sending->save();
    }


    //格式化条件邀请配置
    public function formatCondition($condition)
    {
        if (!empty($condition['out']['corp_tag_ids'])) {
            $condition['out']['corp_tag_ids_array'] = $this->corpTagService->getTagsByIds($condition['out']['corp_tag_ids']);
        }
        if (!empty($condition['isset']['corp_tag_ids'])) {
            $condition['isset']['corp_tag_ids_array'] = $this->corpTagService->getTagsByIds($condition['out']['corp_tag_ids']);
        }
        if (!empty($condition['out'])) {
            if ($condition['out']['sex'] == 0) {
                $sex = "未知";
            } else if ($condition['out']['sex'] == 1) {
                $sex = "男";
            } else if ($condition['out']['sex'] == 2) {
                $sex = "女";
            }
            $condition['out']['sex'] = $sex;
            if ($condition['out']['is_with_remarks'] == 1) {
                $is_with_remarks = "是";
            } else {
                $is_with_remarks = "否";
            }
            $condition['out']['is_with_remarks'] = $is_with_remarks;
        }
        if (!empty($condition['isset'])) {
            if ($condition['isset']['sex'] == 0) {
                $sex = "未知";
            } else if ($condition['isset']['sex'] == 1) {
                $sex = "男";
            } else if ($condition['isset']['sex'] == 2) {
                $sex = "女";
            }
            $condition['isset']['sex'] = $sex;
            if ($condition['isset']['is_with_remarks'] == 1) {
                $is_with_remarks = "是";
            } else {
                $is_with_remarks = "否";
            }
            $condition['isset']['is_with_remarks'] = $is_with_remarks;
        }
        if (!empty($condition['isset']['corp_tag_ids'])) {
            $condition['isset']['corp_tag_ids_array'] = $this->corpTagService->getTagsByIds($condition['out']['corp_tag_ids']);
        }
        return $condition;
    }


    //格式化邀请配置列表方便调用
    public function formatConditionToText($condition)
    {
        if (empty($condition)) {
            return null;
        }
        if (!empty($condition['crowd_conf']) && !empty($condition['crowd_conf']['type']) && $condition['crowd_conf']['type'] == 2) {
            if(!empty($condition['crowd_conf']['conf'])){
                foreach ($condition['crowd_conf']['conf'] as $key => $item) {
                    if (!empty($item['isset'])) {
                        $condition['crowd_conf']['conf'][$key]['isset']['room_tag']['ids_array'] = $this->ChRoomTagService->getTagsByIds($item['isset']['room_tag']['ids']);
                        if ($item['isset']['member_type'] == 0) {
                            $member_type = "群主/管理员";
                        } else if ($item['isset']['member_type'] == 1) {
                            $member_type = "群主";
                        } else {
                            $member_type = "成员";
                        }
                        $condition['crowd_conf']['conf'][$key]['isset']['member_type_text'] = $member_type;
                    }
                    if (!empty($item['out'])) {
                        $condition['crowd_conf']['conf'][$key]['out']['room_tag']['ids_array'] = $this->ChRoomTagService->getTagsByIds($item['out']['room_tag']['ids']);
                        if ($item['out']['member_type'] == 0) {
                            $member_type = "群主/管理员";
                        } else if ($item['out']['member_type'] == 1) {
                            $member_type = "群主";
                        } else {
                            $member_type = "成员";
                        }
                        $condition['crowd_conf']['conf'][$key]['out']['member_type_text'] = $member_type;
                    }
                }
            }
        }

        if (!empty($condition['custom_conf']) && !empty($condition['custom_conf']['type']) && $condition['custom_conf']['type'] == 2) {
            $sex = "";
            if(!empty($condition['custom_conf']['conf'])){
                foreach ($condition['custom_conf']['conf'] as $key => $item) {
                    if (!empty($item['isset'])) {
                        if ($item['isset']['gender'] == 0) {
                            $sex = "未知";
                        } else if ($item['isset']['gender'] == 1) {
                            $sex = "男";
                        } else if ($item['isset']['gender'] == 2) {
                            $sex = "女";
                        }
                        if ($item['isset']['corp_match_type'] == 0) {
                            $corp_match_type = "满足任意企微标签";
                        } else if ($item['isset']['corp_match_type'] == 1) {
                            $corp_match_type = "满足所有企微标签 ";
                        } else if ($item['isset']['corp_match_type'] == 2) {
                            $corp_match_type = "未打企微标签";
                        }
                        if ($item['isset']['smart_match_type'] == 0) {
                            $smart_match_type = "满足任意智能标签";
                        } else if ($item['isset']['smart_match_type'] == 1) {
                            $smart_match_type = "满足所有智能标签 ";
                        } else if ($item['isset']['smart_match_type'] == 2) {
                            $smart_match_type = "未打智能标签";
                        }
                        $condition['custom_conf']['conf'][$key]['isset']['gender_text'] = $sex;
                        $condition['custom_conf']['conf'][$key]['isset']['corp_match_type_text'] = $corp_match_type;
                        $condition['custom_conf']['conf'][$key]['isset']['smart_match_type_text'] = $smart_match_type;

                        var_dump('哈哈哈哈哈哈');
                        var_dump($item['isset']['corp_tag_ids']);
                        if(!empty($item['isset']['corp_tag_ids'])){
                            if(!empty($item['isset']['corp_tag_ids'][0]['corp_id'])){
                                foreach ($item['isset']['corp_tag_ids'] as $k=>$tagIdsInfo){
                                    $condition['custom_conf']['conf'][$key]['isset']['corp_tag_ids'][$k]['corp_info']=$this->chCorpMapper->findById($tagIdsInfo['corp_id']);
                                    $condition['custom_conf']['conf'][$key]['isset']['corp_tag_ids'][$k]['corp_tag_array']=$this->corpTagService->getTagsByIds($tagIdsInfo['ids']);
                                }
                            }else{
                                $condition['custom_conf']['conf'][$key]['isset']['corp_tag_ids_array'] = $this->corpTagService->getTagsByIds($item['isset']['corp_tag_ids']);
                            }
                        };
                        !empty($item['isset']['smart_tag_ids']) && $condition['custom_conf']['conf'][$key]['isset']['smart_tag_id_array'] = $this->ChSmartTagService->getTagsByIds($item['isset']['smart_tag_ids']);
                    }
                    if (!empty($item['out'])) {
                        if ($item['out']['gender'] == 0) {
                            $sex = "未知";
                        } else if ($item['out']['gender'] == 1) {
                            $sex = "男";
                        } else if ($item['out']['gender'] == 2) {
                            $sex = "女";
                        }
                        if ($item['out']['corp_match_type'] == 0) {
                            $corp_match_type = "满足任意企微标签";
                        } else if ($item['out']['corp_match_type'] == 1) {
                            $corp_match_type = "满足所有企微标签 ";
                        } else if ($item['out']['corp_match_type'] == 2) {
                            $corp_match_type = "未打企微标签";
                        }
                        if ($item['out']['smart_match_type'] == 0) {
                            $smart_match_type = "满足任意智能标签";
                        } else if ($item['out']['smart_match_type'] == 1) {
                            $smart_match_type = "满足所有智能标签 ";
                        } else if ($item['out']['smart_match_type'] == 2) {
                            $smart_match_type = "未打智能标签";
                        }
                        $condition['custom_conf']['conf'][$key]['out']['gender_text'] = $sex;
                        $condition['custom_conf']['conf'][$key]['out']['corp_match_type_text'] = $corp_match_type;
                        $condition['custom_conf']['conf'][$key]['out']['smart_match_type_text'] = $smart_match_type;
                        if(!empty($item['out']['corp_tag_ids'])){
                            if(!empty($item['out']['corp_tag_ids'][0]['corp_id'])){
                                foreach ($item['out']['corp_tag_ids'] as $k=>$tagIdsInfo){
                                    $condition['custom_conf']['conf'][$key]['out']['corp_tag_ids'][$k]['corp_info']=$this->chCorpMapper->findById($tagIdsInfo['corp_id']);
                                    $condition['custom_conf']['conf'][$key]['out']['corp_tag_ids'][$k]['corp_tag_array']=$this->corpTagService->getTagsByIds($tagIdsInfo['ids']);
                                }
                            }else{
                                $condition['custom_conf']['conf'][$key]['out']['corp_tag_ids_array'] = $this->corpTagService->getTagsByIds($item['out']['corp_tag_ids']);
                            }
                        };
                        !empty($item['out']['smart_tag_ids']) && $condition['custom_conf']['conf'][$key]['out']['smart_tag_id_array'] = $this->ChSmartTagService->getTagsByIds($item['out']['smart_tag_ids']);
                    }
                }
            }

        }
        return $condition;
    }


    //格式化邀请配置列表方便调用
    public function formatConditionToText2($condition)
    {
        if (empty($condition)) {
            return null;
        }
        if (!empty($condition['crowd_conf']) && $condition['crowd_conf']['type'] == 2) {
            if (!empty($condition['crowd_conf']['conf']['isset'])) {
                $condition['crowd_conf']['conf']['isset']['room_tag']['ids_array'] = $this->ChRoomTagService->getTagsByIds($condition['crowd_conf']['conf']['isset']['room_tag']['ids']);
                if ($condition['crowd_conf']['conf']['isset']['member_type'] == 0) {
                    $member_type = "群主/管理员";
                } else if ($condition['crowd_conf']['conf']['isset']['member_type'] == 1) {
                    $member_type = "群主";
                } else {
                    $member_type = "成员";
                }
                $condition['crowd_conf']['conf']['isset']['member_type_text'] = $member_type;
            }
            if (!empty($condition['crowd_conf']['conf']['out'])) {
                $condition['crowd_conf']['conf']['out']['room_tag']['ids_array'] = $this->ChRoomTagService->getTagsByIds($condition['crowd_conf']['conf']['out']['room_tag']['ids']);
                if ($condition['crowd_conf']['conf']['out']['member_type'] == 0) {
                    $member_type = "群主/管理员";
                } else if ($condition['crowd_conf']['conf']['out']['member_type'] == 1) {
                    $member_type = "群主";
                } else {
                    $member_type = "成员";
                }
                $condition['crowd_conf']['conf']['out']['member_type_text'] = $member_type;
            }
        }

        if (!empty($condition['custom_conf']) && $condition['custom_conf']['type'] == 2) {
            $sex = "";
            if (!empty($condition['custom_conf']['conf']['isset'])) {
                if ($condition['custom_conf']['conf']['isset']['gender'] == 0) {
                    $sex = "未知";
                } else if ($condition['custom_conf']['conf']['isset']['gender'] == 1) {
                    $sex = "男";
                } else if ($condition['custom_conf']['conf']['isset']['gender'] == 2) {
                    $sex = "女";
                }
                if ($condition['custom_conf']['conf']['isset']['corp_match_type'] == 0) {
                    $corp_match_type = "满足任意企微标签";
                } else if ($condition['custom_conf']['conf']['isset']['corp_match_type'] == 1) {
                    $corp_match_type = "满足所有企微标签 ";
                } else if ($condition['custom_conf']['conf']['isset']['corp_match_type'] == 2) {
                    $corp_match_type = "未打企微标签";
                }
                if ($condition['custom_conf']['conf']['isset']['smart_match_type'] == 0) {
                    $smart_match_type = "满足任意智能标签";
                } else if ($condition['custom_conf']['conf']['isset']['smart_match_type'] == 1) {
                    $smart_match_type = "满足所有智能标签 ";
                } else if ($condition['custom_conf']['conf']['isset']['smart_match_type'] == 2) {
                    $smart_match_type = "未打智能标签";
                }
                $condition['custom_conf']['conf']['isset']['gender_text'] = $sex;
                $condition['custom_conf']['conf']['isset']['corp_match_type_text'] = $corp_match_type;
                $condition['custom_conf']['conf']['isset']['smart_match_type_text'] = $smart_match_type;

                if(!empty($condition['custom_conf']['conf']['isset']['corp_tag_ids'])){
                    if(!empty($condition['custom_conf']['conf']['isset']['corp_tag_ids'][0]['corp_id'])){
                        foreach ($condition['custom_conf']['conf']['isset']['corp_tag_ids'] as $k=>$tagIdsInfo){
                            $condition['custom_conf']['conf']['isset']['corp_tag_ids'][$k]['corp_info']=$this->chCorpMapper->findById($tagIdsInfo['corp_id']);
                            $condition['custom_conf']['conf']['isset']['corp_tag_ids'][$k]['corp_tag_array']=$this->corpTagService->getTagsByIds($tagIdsInfo['ids']);
                        }
                    }else{
                        $condition['custom_conf']['conf']['isset']['corp_tag_ids_array'] = $this->corpTagService->getTagsByIds($condition['custom_conf']['conf']['isset']['corp_tag_ids']);
                    }
                }
                !empty($condition['custom_conf']['conf']['isset']['smart_tag_ids']) && $condition['custom_conf']['conf']['isset']['smart_tag_id_array'] = $this->ChSmartTagService->getTagsByIds($condition['custom_conf']['conf']['isset']['smart_tag_ids']);
            }
            if (!empty($condition['custom_conf']['conf']['out'])) {
                if ($condition['custom_conf']['conf']['out']['gender'] == 0) {
                    $sex = "未知";
                } else if ($condition['custom_conf']['conf']['out']['gender'] == 1) {
                    $sex = "男";
                } else if ($condition['custom_conf']['conf']['out']['gender'] == 2) {
                    $sex = "女";
                }
                if ($condition['custom_conf']['conf']['out']['corp_match_type'] == 0) {
                    $corp_match_type = "满足任意企微标签";
                } else if ($condition['custom_conf']['conf']['out']['corp_match_type'] == 1) {
                    $corp_match_type = "满足所有企微标签 ";
                } else if ($condition['custom_conf']['conf']['out']['corp_match_type'] == 2) {
                    $corp_match_type = "未打企微标签";
                }
                if ($condition['custom_conf']['conf']['out']['smart_match_type'] == 0) {
                    $smart_match_type = "满足任意智能标签";
                } else if ($condition['custom_conf']['conf']['out']['smart_match_type'] == 1) {
                    $smart_match_type = "满足所有智能标签 ";
                } else if ($condition['custom_conf']['conf']['out']['smart_match_type'] == 2) {
                    $smart_match_type = "未打智能标签";
                }
                $condition['custom_conf']['conf']['out']['gender_text'] = $sex;
                $condition['custom_conf']['conf']['out']['corp_match_type_text'] = $corp_match_type;
                $condition['custom_conf']['conf']['out']['smart_match_type_text'] = $smart_match_type;
                if( !empty($condition['custom_conf']['conf']['out']['corp_tag_ids'])){
                    if(!empty($condition['custom_conf']['conf']['out']['corp_tag_ids'][0]['corp_id'])){
                        foreach ($condition['custom_conf']['conf']['out']['corp_tag_ids'] as $k=>$tagIdsInfo){
                            $condition['custom_conf']['conf']['out']['corp_tag_ids'][$k]['corp_info']=$this->chCorpMapper->findById($tagIdsInfo['corp_id']);
                            $condition['custom_conf']['conf']['out']['corp_tag_ids'][$k]['corp_tag_array']=$this->corpTagService->getTagsByIds($tagIdsInfo['ids']);
                        }
                    }else{
                        $condition['custom_conf']['conf']['out']['corp_tag_ids_array'] = $this->corpTagService->getTagsByIds($condition['custom_conf']['conf']['out']['corp_tag_ids']);
                    }
                };
                !empty($condition['custom_conf']['conf']['out']['smart_tag_ids']) && $condition['custom_conf']['conf']['out']['smart_tag_id_array'] = $this->ChSmartTagService->getTagsByIds($condition['custom_conf']['conf']['out']['smart_tag_ids']);
            }
        }
        return $condition;
    }

}